<template>
  <div class="app-container" style="margin-top: 10px;">
    <el-card style="width: 100%;">
      <el-form :model="matterInfo" ref="formRef" :rules="rules" style="margin-top: 5px;width: 95%" label-width="180px">
          <!--事项信息-->
          <div>
            <ElLine :title="'事项信息'" style="font-size: 20px;margin: 10px 0"></ElLine>
            <div>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="工作任务" prop="relatedIndicatorOrTaskId">
                    <el-select v-model="matterInfo.relatedIndicatorOrTaskId" placeholder="请选择" filterable>
                      <el-option
                          v-for="task in workTaskList"
                          :key="task.targetTaskId"
                          :label="task.targetTaskName"
                          :value="task.targetTaskId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="24">
                  <el-form-item label="事项名称" prop="matterName">
                    <el-input v-model="matterInfo.matterName" placeholder="请输入"/>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row justify="space-between">
                <el-col :span="11">
                  <el-form-item label="事项负责人" prop="matterResponsibleId">
                    <el-select v-model="matterInfo.matterResponsibleId" placeholder="请选择"
                                @focus="fetchRelatedPolicies" @change="handleSelectChange" filterable>
                      <el-option
                          v-for="policy in user"
                          :key="policy.value"
                          :label="policy.label"
                          :value="policy.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="完成期限" prop="completionDeadline">
                    <el-date-picker
                        v-model="matterInfo.completionDeadline"
                        type="date"
                        style="width: 100%;"
                        placeholder="请选择完成期限"
                        format="YYYY/MM/DD"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row justify="space-between">
                <el-col :span="11">
                  <el-form-item label="事项关联人" prop="em2">
                    <el-input disabled v-model="matterInfo.em2" placeholder="请先选择事项负责人"/>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="关联法律" prop="relatedLawId">
                    <el-select v-model="matterInfo.relatedLawId" placeholder="请选择" clearable filterable>
                      <el-option
                          v-for="law in laws"
                          :key="law.value"
                          :label="law.label"
                          :value="law.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row justify="space-between">
                <el-col :span="11">
                  <el-form-item label="归属部门" prop="deptId">
                    <el-input disabled v-model="matterInfo.dept" placeholder="请先选择事项负责人"/>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="关联制度" prop="relatedPolicyId">
                    <el-select filterable v-model="matterInfo.relatedPolicyId" placeholder="请选择" @focus="systemManage" clearable >
                      <el-option
                          v-for="policy in relatedPolicies"
                          :key="policy.value"
                          :label="policy.label"
                          :value="policy.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row justify="space-between">
                <el-col :span="11">
                  <el-form-item label="关键节点类型" prop="workContentType">
                    <el-radio-group v-model="matterInfo.workContentType">
                      <el-radio label="0">市场类</el-radio>
                      <el-radio label="1">非市场类</el-radio>
                      <!-- 添加其他单选按钮选项 -->
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="是否成立专班" prop="isSpecialTeamFormed">
                    <el-radio-group v-model="matterInfo.isSpecialTeamFormed">
                      <el-radio label="0">是</el-radio>
                      <el-radio label="1">否</el-radio>
                      <!-- 添加其他单选按钮选项 -->
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        <div class="button-container">
          <el-button type="primary" @click="validateForm">保 存</el-button>
          <el-button type="info" @click="clearForm" style="margin-left: 50px;">清 空</el-button>
          <el-button type="danger" @click="close" style="margin-left: 50px;">关 闭</el-button>
        </div>
      </el-form>
        <el-table v-loading="loading" :data="matterList">
        <el-table-column min-width="5%" type="index" label="序号" align="center"/>
        <el-table-column  min-width="10%" label="事项名称" prop="matterName"/>
        <el-table-column min-width="5%" label="负责人" align="center" prop="matterResponsible"/>
        <el-table-column min-width="6%" label="事项完成期限" align="center" prop="completionDeadline" :formatter="formatDate"/>
        <el-table-column min-width="5%" label="状态" align="center">
          <template #default="scope">
            <dict-tag :options="task_status" :value="scope.row.em4"/>
          </template>
        </el-table-column>
        <el-table-column min-width="8%" label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" @click="handleTask(scope.row)">创建任务</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>
<script>
import {reactive, toRefs, ref, getCurrentInstance, } from 'vue';
import {ElInput, ElSelect, ElOption, ElRow, ElCol, ElForm, ElFormItem, ElButton, ElMessageBox} from 'element-plus';
import {addMatter, getSystemManage} from "@/api/matter/matter";
import {listMatter, updateMatterEm4 } from "@/api/matter/matter";
import {getTargetTaskList} from "@/api/targetTask/targetTask.js";
import {getUsers} from "@/api/matter/users.js";
import {getInfo} from "@/api/login.js";
import {getUser} from "@/api/system/user.js";

export default {
  name: "createMatter",
  components: {
    ElInput,
    ElSelect,
    ElOption,
    ElRow,
    ElCol,
    ElForm,
    ElFormItem,
    ElButton,
    ElMessageBox
  },
  setup() {
    const {proxy} = getCurrentInstance(); // 确保 proxy 获取正确
    const {related_law} = proxy.useDict('related_law');
    // 定义初始状态常量
    const initialMatterInfo = {
      matterName: '', //  事项名称
      matterResponsibleId: '', // 事项
      matterRelatedPerson: '', // 事项关联人
      matterRelatedPersonId: '', // 事项关联人 id
      em2: '', // 事项关联人
      em4: '1', // 事项状态
      em5: '0', // 事项催办状态
      dept: '',
      deptId: '', // 部门
      relatedLawId: '', // 关联法律
      relatedPolicyId: '', // 关联制度
      relatedIndicatorOrTaskType: '1', //关联指标或任务类型
      relatedIndicatorOrTaskId: null, // 关联指标或任务类型id
      workContentType: '1', // 工作内容类型
      isSpecialTeamFormed: '1', // 是否成立专班
      completionDeadline: '', // 事项完成期限
    };

    const data = reactive({
      matterInfo: initialMatterInfo,
      rules: {
        matterName: [{required: true, message: "事项名称不能为空", trigger: "blur"}],
        matterResponsibleId: [{required: true, message: "事项负责人不能为空", trigger: "blur"}],
        em2: [{required: true, message: "事项关联人不能为空", trigger: "blur"}],
        deptId: [{required: true, message: "归属部门不能为空", trigger: "blur"}],
        // relatedLawId: [{required: true, message: "关联法律不能为空", trigger: "blur"}],
        // relatedPolicyId: [{required: true, message: "关联制度不能为空", trigger: "blur"}],
        relatedIndicatorOrTaskId: [{required: true, message: "工作任务不能为空", trigger: "change"}],
        workContentType: [{required: false}],
        isSpecialTeamFormed: [{required: false}],
        completionDeadline: [{required: true, message: "完成期限不能为空", trigger: "change"}]
      },
      departments: [], // 存储部门选项
      laws: related_law,// 存储法律法规选项
      user: [],// 存储用户选项
      relatedPolicies: [], // 存储关联制度选项
      relatedTasks: [], // 存储相关指标或任务选项
      workTaskList: [],// 工作任务集合
      deptType:'0', // 部门类型 0企业 1政府
      matterList: [],//事项列表
      loading: true,//列表加载
      total: 0,//列表总条数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        relatedIndicatorOrTaskId: null
      },
    });

    // 事项负责人
    const fetchRelatedPolicies = () => {
      return new Promise((resolve, reject) => {
        getUsers().then(response => {
          if (response.code === 200) {
            data.user = response.data;
            console.log(data.user); // 这里改成打印正确的数据
            resolve(); // 成功获取数据后 resolve
          } else {
            proxy.$modal.msgError(result.msg);
            reject(new Error('Failed to fetch policies')); // 失败时 reject，并传递错误信息
          }
        }).catch(error => {
          console.error('Error fetching policies:', error);
          reject(error); // 捕获任何异常，并将其作为错误对象传递给 reject
        });
      });
    };
    const formRef = ref(null);


    // 表单验证方法
    const validateForm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          addMatter(data.matterInfo).then(response => {
            if (response.code === 200) {
              proxy.$modal.msgSuccess("事项创建成功");
              Object.assign(data.matterInfo, initialMatterInfo); // 将 matterInfo 重置为初始状态
              formRef.value.resetFields(); // 重置表单验证状态
            } else {
              proxy.$modal.msgError(result.msg);
            }
          });
        } else {
          return false;
        }
      });
    };

    // 选择事项后触发方法
    const handleSelectChange = (selectedId) => {
      // 根据选中的ID获取整个policy对象
      const selectedPolicy = data.user.find(policy => policy.value === selectedId);
      if (selectedPolicy) {
        // console.log('选中的政策对象：', selectedPolicy);
        data.matterInfo.matterRelatedPerson = selectedPolicy.superior
        data.matterInfo.em2 = selectedPolicy.superior // 事项关联人
        data.matterInfo.dept = selectedPolicy.dept
        data.matterInfo.deptId = selectedPolicy.deptId
      }
    };

    // 关联制度
    const systemManage = () => {
      getSystemManage().then(response => {
        if (response.code === 200) {
          data.relatedPolicies = response.data
        } else {
          proxy.$modal.msgError(result.msg);
        }
      });

    };

    // 清空表单
    const clearForm = () => {
      Object.assign(data.matterInfo, initialMatterInfo); // 将 matterInfo 重置为初始状态
      formRef.value.resetFields(); // 重置表单验证状态
    };

      //查询列表
    const getList = () => {
      data.loading = true;
      listMatter(data.queryParams).then((response) => {
        data.matterList = response.data.list;
        data.total = response.data.total;
        data.loading = false;
      });
    };
    
    const getWorkTaskList = () => {
      getTargetTaskList().then(res => {
        if (res.code == 200) {
          data.workTaskList = res.data;
        }
      })
    };
    // 获取当前登录人部门类型 企业/政府 如果为政府只能选非市场类
    const getUserInfo = ()=>{
      getInfo().then(res => {
        if (res.code == 200) {
          if (res.user != null) {
            getUser(res.user.userId).then(res1 => {
              if (res1.data && res1.data.dept && res1.data.dept.deptType) {
                data.deptType = res1.data.dept.deptType;
                if (data.deptType == 1) {
                  data.matterInfo.workContentType = '1';
                }
              }
            });
          }
        }
      })
    }
    const route = useRoute();
    watch(() => route.query.targetTaskId, (newVal) => { 
      data.matterInfo.relatedIndicatorOrTaskId = Number(newVal) || null;
    }, {  
      immediate: true // 立即以当前的query值触发回调函数  
    });
    // 监听data.matterInfo.relatedIndicatorOrTaskId的变化  
    watch(() => data.matterInfo.relatedIndicatorOrTaskId, (newVal) => {  
      data.queryParams.relatedIndicatorOrTaskId = newVal;
      getList(data.queryParams)
    }, {  
      immediate: true
    });
    /** 关闭按钮 */
    function close() {
      proxy.$tab.closePage();
    };
    function create(){
      getWorkTaskList();
      getUserInfo();
    }
    create();
    return {
      ...toRefs(data),
      formRef,
      getList,
      validateForm,
      fetchRelatedPolicies,
      clearForm,
      handleSelectChange,
      systemManage,
      close
    };
  }
};
</script>
<style scoped>
.divider {
  border: none;
  border-top: 1px solid #d3d3d3; /* 灰色分割线，设置粗细 */
  width: 95%; /* 设置分割线长度 */
  margin: 30px 0; /* 上下间距 */
  position: relative;
  left: 1%; /* 向左移动 */
}

.button-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  margin: 10px 0; /* 上边距 */
}
.app-container {
  padding: 3px;
  margin-left: 20px;
  margin-right: 20px;
}
</style>
